import 'dart:async';
import 'package:flutter/material.dart';

class main_page extends StatefulWidget {
  const main_page({super.key});

  @override
  State<main_page> createState() => _LoadMoreExampleState();
}

class _LoadMoreExampleState extends State<main_page> {
  bool _isLoading = false;
  ScrollController _scrollController = ScrollController();

  // 模拟数据
  List<String> _data = List.generate(20, (index) => 'Item $index');

  // 刷新数据的异步方法
  Future<void> _refreshData() async {
    // await Future.delayed(Duration(seconds: 2)); // 模拟网络请求

    setState(() {
      _data = [];
      for (int i = 0; i < 20; i++) {
        _data.add('Item $i');
      }
    });
  }

  late Timer periodicTimer;
  num indexNum = 1;
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);

    periodicTimer = Timer.periodic(Duration(seconds: 2), (Timer timer) {
      // 每2秒执行一次的任务
      // print('每2秒执行一次的任务');
      if (_isOverPage) {
        return;
      }
      setState(() {
        indexNum++;
        if (indexNum > 5) {
          indexNum = 1;
        }
        _rootBack = "assets/images/image_" + indexNum.toString() + ".jpg";
      });
      // 如果需要取消定时器，可以调用 timer.cancel();
    });

// _controller = AnimationController(
//       duration: const Duration(seconds: 2),
//       vsync: this,
//     )..repeat(reverse: true); // 往返动画

    // _animation = Tween<double>(begin: 0.0, end: 1.0).animate(
    //   CurvedAnimation(
    //     parent: _controller,
    //     curve: Curves.easeInOut,
    //   ),
    // );
  }

  // 监听滚动位置, 判断是否滚动到列表底部
  void _scrollListener() {
    if (_scrollController.position.pixels ==
            _scrollController.position.maxScrollExtent &&
        !_isLoading) {
      _loadMoreData();
    }
  }

  bool _isOverPage = false;
  // 模拟加载更多数据
  Future<void> _loadMoreData() async {
    setState(() {
      _isLoading = true;
    });
    await Future.delayed(Duration(seconds: 2)); // 模拟网络请求
    setState(() {
      _data.addAll(
          List.generate(10, (index) => 'New Item ${_data.length + index}'));
      _isLoading = false;
    });
  }

  @override
  void dispose() {
    //  _controller.dispose();
    periodicTimer.cancel();
    _isOverPage = true;
    _scrollController.dispose();
    super.dispose();
  }

// Container(
//       width: MediaQuery.of(context).size.width,
//       height: MediaQuery.of(context).size.height,
//       decoration: const BoxDecoration(
//           image: DecorationImage(
//               opacity: 0.5,
//               image: AssetImage('assets/images/image_2.jpg'),
//               fit: BoxFit.cover)),
//       child: _bannerlayout(context),
//     );

  // late AnimationController _controller;
  // late Animation<double> _animation;

  @override
  // Widget build(BuildContext context) {
  Widget build(BuildContext context) {
    // return _RootView();
    return CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(
          title: const Text('首页'),
          expandedHeight: 200,
          pinned: true,
          floating: true,
          flexibleSpace: FlexibleSpaceBar(
            background:
                Image.asset('assets/images/image_1.jpg', fit: BoxFit.cover),
          ),
        ),
        SliverGrid(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 6,
            crossAxisSpacing: 5,
            mainAxisSpacing: 5,
          ),
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              return Container(
                  padding: const EdgeInsets.all(10.0),
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(10.0), // 设置圆角半径为20.0
                      child: Image.asset(
                          'assets/images/bg_imaeg_' +
                              (index + 1).toString() +
                              '.jpg',
                          width: 55,
                          height: 55,
                          fit: BoxFit.cover)));
            },
            childCount: 6,
          ),
        ),

        // 列表部分
        SliverList(
          delegate: SliverChildListDelegate(
            List.generate(
              3,
              (index) => ListBody(
                children: [
                  const SizedBox(
                    height: 10,
                  ),
                  Image.asset(
                    "assets/images/bg_imaeg_" + (index + 1).toString() + ".jpg",
                    height: 100,
                    fit: BoxFit.cover,
                  )
                ],
              ),
            ),
          ),
        ),
        // 网格部分
        SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
          ),
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              return Card(
                child: Center(
                  child: Text('Grid Item $index'),
                ),
              );
            },
            childCount: 20,
          ),
        ),
      ],
    );
    // NestedScrollView(
    //     headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
    //       return <Widget>[
    //         SliverAppBar(
    //           title: Text('首页内容'),
    //           floating: true,
    //           pinned: true,
    //           expandedHeight: 200,
    //           flexibleSpace: FlexibleSpaceBar(
    //             background: Image.asset(
    //               _rootBack,
    //               fit: BoxFit.cover,
    //             ),
    //           ),
    //         ),
    //       ];
    //     },
    //     body: _bodyGridView());

    // return Container(
    //   width: MediaQuery.of(context).size.width,
    //   height: MediaQuery.of(context).size.height,
    //   decoration: BoxDecoration(
    //       image: DecorationImage(
    //           opacity: 0.3, image: AssetImage(_rootBack), fit: BoxFit.cover)),
    //   child: _RootView(),
    // );
  }

  // Widget _bodyGridView() {
  //   return
  // }
  // Widget _exportView() {
  //   return Expanded(
  //       child: Container(
  //           color: Colors.white10,
  //           child: Center(
  //               child: ListView.builder(
  //                   controller: _scrollController,
  //                   itemCount: _data.length,
  //                   itemBuilder: (context, index) {
  //                     return ListTile(
  //                       title: Text(_data[index]),
  //                     );
  //                   }))));
  // }

  String _rootBack = "assets/images/image_3.jpg";
  // Widget _RootView() {
  //   return Column(
  //     children: [
  //       Image.asset(
  //         _rootBack,
  //         fit: BoxFit.cover,
  //         height: 150,
  //         width: MediaQuery.of(context).size.width,
  //       ),
  //       Text('咋没有了呢？'),
  //       // _banner(),
  //       //  _listView(),
  //       //  _productList()
  //     ],
  //   );
  // }

  Widget bodyColumn() {
    return Column(
      children: [
        const SizedBox(
          height: 16,
        ),
        _ItemTitle("可选栏目"),
        const SizedBox(
          height: 5,
        ),
        _ItemImageList(),
        const SizedBox(
          height: 10,
        ),
        _ItemTitle("可选商品"),
        const SizedBox(
          height: 5,
        )
      ],
    );
  }

  Widget _listView() {
    return ListView.builder(
      controller: _scrollController,
      itemCount: _data.length + 1,
      itemBuilder: (context, index) {
        if (index == _data.length) {
          return _isLoading
              ? Center(
                  child: Column(
                  children: const [
                    CircularProgressIndicator(),
                    SizedBox(
                      height: 15,
                    )
                  ],
                )) // 显示加载中的进度条
              : const SizedBox(); // 空白占位
        }

        return ListTile(
          title: Text(_data[index]),
        );
      },
    );
  }
  // Widget _RootView2() {
  //   return NestedScrollView(
  //     headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
  //       return <Widget>[
  //         SliverAppBar(
  //           title: Text('NestedScrollView 示例'),
  //           pinned: true,
  //           expandedHeight: 200.0,
  //           flexibleSpace: FlexibleSpaceBar(
  //               background: Image.asset(
  //             'assets/images/image_1.jpg',
  //             width: double.infinity,
  //             height: double.infinity,
  //             fit: BoxFit.cover,
  //           )),
  //         ),
  //       ];
  //     },
  //     body: SliverList(
  //       delegate: SliverChildBuilderDelegate(
  //         (BuildContext context, int index) {
  //           return ListTile(
  //             title: Text('列表项 $index'),
  //           );
  //         },
  //         childCount: 50,
  //       ),
  //     ),
  //   );
  // }

  // Widget _banner() {

  //   return Swiper(
  //     itemBuilder: (BuildContext context, int index) {
  //       return Image.asset(
  //         "assets/banner/image_banner_" +
  //             (index + 1).toString() +
  //             ".jpg", // 替换为你的图片URL
  //         fit: BoxFit.cover,
  //       );
  //     },
  //     itemCount: 9, // 图片数量
  //     autoplay: true, // 自动播放
  //     pagination: SwiperPagination(), // 分页指示器
  //     control: SwiperControl(), // 切换控制
  //     itemHeight: 150,
  //   );
  // }

  Widget _productList() {
    final List<String> items = List.generate(100, (index) => 'Item $index');

    return Builder(builder: (BuildContext context) {
      return GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2, // 每行显示2个子项
            crossAxisSpacing: 4.0, // 交叉轴间距
            mainAxisSpacing: 4.0, // 主轴间距
          ),
          itemCount: items.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  items[index],
                  style: TextStyle(fontSize: 18.0),
                ),
              ),
            );
          });
    });
  }

  Widget _ItemTitle(String title) {
    return Row(
      children: [
        const SizedBox(
          width: 16,
        ),
        Text(
          title,
          style: TextStyle(fontSize: 14, color: Color.fromRGBO(0, 0, 0, 1)),
        )
      ],
    );
  }

  Widget _ItemImageList() {
    return Row(
      children: [
        const SizedBox(
          width: 16,
        ),
        Card(
          elevation: 8.0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          // image:Image.asset(
          //       'assets/images/image_1.jpg',
          //       fit: BoxFit.cover,
          //     ),
          child: Container(
              padding: const EdgeInsets.all(10.0),
              width: 80,
              height: 80,
              child: Image.asset(
                'assets/images/image_1.jpg',
                fit: BoxFit.cover,
              )),
        ),
        const SizedBox(
          width: 16,
        ),
        ClipRRect(
            borderRadius: BorderRadius.circular(10.0), // 设置圆角半径为20.0
            child: Image.asset('assets/images/image_2.jpg',
                width: 65, height: 65, fit: BoxFit.cover)),
        const SizedBox(
          width: 16,
        ),
        ClipRRect(
            borderRadius: BorderRadius.circular(40.0), // 设置圆角半径为20.0
            child: Image.asset('assets/images/image_3.jpg',
                width: 65, height: 65, fit: BoxFit.cover)),
        const SizedBox(
          width: 16,
        ),
        Image.asset('assets/images/image_4.jpg',
            width: 65, height: 65, fit: BoxFit.cover),
        const SizedBox(
          width: 16,
        ),
      ],
    );
  }
}
